﻿#include "editor/resview.h"
#include "editor/imview.h"
#include "seqbase/store.h"
#include "ui/controls.h"
#include "ui/native_dialogs.h"

using namespace std;
using namespace anip;

editor::ResourceView::ResourceView(Container* parent, SDirectory& dir, invec2 size):
	EditorWindow(parent, size, L"资源管理器")
{
	auto& btn = addCloseButton();
	btn.texture = Settings::closeButtonTexture.get();

	auto menu = new ui::MenuBar(this);
	ui::MenuHelper::barButton(*menu, L"导入……",
		[&](ui::MenuBar::Item& self)
		{
			wstring out = ui::native::openFileDialog(L""s, L""s, {
						{L"Image files (*.jpg, *.jpeg, *.png, *.bmp, *.tga, *.psd)",
							L"*.jpg;*.jpeg;*.png;*.bmp;*.tga;*.psd"},
						{L"All files", L"*.*"} }, 0);
			if (!out.empty())
			{
				Texture2D* tex = nullptr;
				try
				{
					tex = Texture2D::createFromFile(ws2utf8s(out));
				}
				catch (exception& ex)
				{
					ui::native::messageBox(utf8s2ws(ex.what()),
						ui::native::MessageType::Error);
					return;
				}

				auto& obj = _currentDir->newTexture(tex);
				obj.isExternal = true;
				obj.path = out;
				size_t pos = out.find_last_of(L'\\') + 1;
				if (pos != string::npos) out = out.substr(pos);
				pos = obj.name.find_last_of(L'.');
				if (pos != string::npos) out = out.substr(pos);
				obj.name = out;
			}
			updateView();
		});

	ui::MenuHelper::barDropdown(*menu, L"新建",
		[&](ui::MenuBar::Item& self)
		{
			auto menu = new ui::Menu(this);
			ui::MenuHelper::button(*menu, L"文件夹", 
				[&](ui::MenuTextItem& self)
				{
					self.menu().markDelete();
					_currentDir->newDirectory(L"新文件夹");
					updateView();
				});
			ui::MenuHelper::separator(*menu);
			ui::MenuHelper::button(*menu, L"图形",
				[&](ui::MenuTextItem& self)
				{
					self.menu().markDelete();
					auto& fg = _currentDir->newFrameGroup(new vg::VgFrameGroup());
					fg.name = L"新图形";
					updateView();
				});
			ui::MenuHelper::button(*menu, L"片段");
			ui::MenuHelper::button(*menu, L"字幕");
			return menu;
		});

	ui::MenuHelper::barDropdown(*menu, L"视图",
		[&](ui::MenuBar::Item& self)
		{
			auto menu = new ui::Menu(this);
			ui::MenuHelper::checkable(*menu, L"缩略图", true);
			ui::MenuHelper::checkable(*menu, L"详细信息", false);
			ui::MenuHelper::checkable(*menu, L"树状图", false);
			return menu;
		});

	_goUpBtn = &ui::MenuHelper::barButton(*menu, L"上一级",
		[&](ui::MenuBar::Item& self)
		{
			_currentDir = _currentDir->parent();
			updateView();
		});

	_view = new ui::ListView(this);
	_view->layoutOptions.dock = Control::LayoutOptions::DockType::Fill;
	_view->allowDrag = true;

	navagateTo(dir);
}

void editor::ResourceView::navagateTo(SDirectory& dir)
{
	_currentDir = &dir;
	_goUpBtn->enabled = dir.parent() != nullptr;
	setText(L"资源管理器 - "s.append(_currentDir->name));
	updateView();
}

void editor::ResourceView::createRenameBoxFor(ui::ListView::Item& i)
{
	auto& ent = *(DataStore::Entity*)i.userData;

	float height = _font.size + 15.0f;
	auto txt = new ui::TextField(this,
		toLocalPos(i.toAbsolutePos()) + vec2{ 0, i.size().y - height },
		{ i.size().x, height });
	txt->setText(i.getText());
	txt->bringToFront();
	txt->focus();
	txt->onDefocus = [&](Control& self)
	{
		wstring s = self.getText();
		if (s.empty()) ui::native::messageBox(
			L"实体名称不能为空", ui::native::MessageType::Error);
		else
		{
			ent.name = s;
			i.setText(s);
		}
		self.markDelete();
	};
	txt->onKeyAction = [&](Control& self, Key k, ButtonAction action)
	{
		if (k == Key::Enter && action == ButtonAction::Down)
		{
			wstring s = self.getText();
			if (s.empty()) ui::native::messageBox(
				L"实体名称不能为空", ui::native::MessageType::Error);
			else
			{
				ent.name = s;
				i.setText(s);
			}
			self.markDelete();
		}
	};
}

void editor::ResourceView::updateView()
{
	_view->clearAllItems();

	for (auto i : _currentDir->entities())
	{
		DataStore::Entity& ent = *i.second;

		auto& item = _view->addItem(ent.name);
		item.userData = &ent;
		item.onMouseButton = [&](Control& self, MouseButton btn, ButtonAction action)
		{
			auto& e = *(DataStore::Entity*)self.userData;
			if (btn == MouseButton::Right && action == ButtonAction::Up)
			{
				auto& menu = ui::MenuHelper::globalMenu(Context::mousePos());
				ui::MenuHelper::button(menu, L"复制");
				ui::MenuHelper::button(menu, L"粘贴");
				ui::MenuHelper::button(menu, L"删除");
				ui::MenuHelper::button(menu, L"重命名",
					[&](ui::MenuTextItem& self)
					{
						self.menu().markDelete();
						createRenameBoxFor(item);
					});
				ui::MenuHelper::separator(menu);
				ui::MenuHelper::button(menu, L"拆散文件夹", 
					[&](ui::MenuTextItem& self)
					{

					}
				).enabled = typeid(e) == typeid(SDirectory&);
				ui::MenuHelper::button(menu, L"装入文件夹",
					[&](ui::MenuTextItem& self)
					{
						
					});
				ui::MenuHelper::separator(menu);
				ui::MenuHelper::button(menu, L"属性");
			}
		};

		if (typeid(ent) == typeid(SDirectory&))
		{
			item.setImage(Settings::folderIconTexture.get());

			item.onDoubleClick = [&](Control& self)
			{
				navagateTo((SDirectory&)ent);
			};
		}
		else if (typeid(ent) == typeid(STexture2D&))
		{
			item.setImage(((STexture2D&)ent).pointer());

			item.onDoubleClick = [&](Control& self)
			{
				new ImageView(topContainer(), item.getImage());
			};
		}
	}
}